<template>
  <el-dialog center :title="getTitle" :visible.sync="innerVisible" :before-close="beforeClose" width="50%">
    <el-row>
      <el-col :span="24">
        <el-form ref="addForm" class="el-form-s el-form-col" :rules="rules" :model="model" label-position="left" label-width="100px">
          <el-row :gutter="15" v-if="!isEdit">
            <el-col :md="12" :lg="12" :xl="12">
              <el-form-item label="师傅姓名:" prop="workerId">
                <el-select
                  v-model="model.workerId"
                  filterable
                  remote
                  clearable
                  reserve-keyword
                  placeholder="请输入关键词搜索"
                  :remote-method="remoteQuery"
                  :loading="searchLoading">
                  <el-option
                    v-for="item in nameArr"
                    :key="item.value"
                    :label="item.text"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :md="12" :lg="12" :xl="12">
              <el-form-item label="师傅姓名:">
                <el-input :value="getWorkerMapValue('workerName')" :disabled="true">
                  <!--<el-input :value="workerNameMap.get(model.workerId)['workerName']" :disabled="true">-->
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :md="12" :lg="12" :xl="12">
              <el-form-item label="登录账号:">
                <el-input :value="getWorkerMapValue('logAccount')"  :disabled="true">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :md="12" :lg="12" :xl="12">
              <el-form-item prop="phone" label="联系手机：">
                <el-input clearable placeholder="输入联系手机" v-model="model.phone"></el-input>
              </el-form-item>
            </el-col>
            <el-col :md="12" :lg="12" :xl="12">
              <el-form-item prop="plateNumber" label="车牌号：">
                <el-input clearable placeholder="请输入车牌号" v-model="model.plateNumber "></el-input>
              </el-form-item>
            </el-col>
            <el-col :md="12" :lg="12" :xl="12">
              <el-form-item label="车辆类型:" prop="carType">
                <el-select v-model="model.carType" placeholder="请选择">
                  <el-option v-for="item in carTypeArr"
                             :key="item.value"
                             :label="item.text"
                             :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :md="12" :lg="12" :xl="12">
              <el-form-item prop="volume" label="车辆体积(m³)" label-width="110px">
                <el-input clearable placeholder="请输入车辆体积" v-model="model.volume"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <template v-for="(item, index) of model.addressArr">
                  <el-col :span="24" :key="index + 'provinceNo'">
                    <el-form-item label="服务省" :prop="'addressArr.' + index + 'provinceNo'">
                      <CascadeAddress v-model="item.provinceNo" @input="getCity(item)" :level="1"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="23" :key="index + 'cityNo'">
                    <el-form-item label="服务市" :prop="'addressArr.' + index + 'cityNo'">
                      <el-checkbox :indeterminate="isIndeterminate"
                                   v-model="item.checkAll"
                                   @change="handleCheckAllChange(item)"
                      >全选</el-checkbox>
                      <el-checkbox-group v-model="item.cityNos" @change="handleCheckedCitiesChange(item)">
                        <el-checkbox v-for="area of item.citys" :label="area.areaNo" :key="area.areaNo">{{area.areaName}}</el-checkbox>
                      </el-checkbox-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="1" :key="index + 'delArr'" v-if="model.addressArr.length > 1">
                    <a href="javascript:void (0);" @click.prevent.stop="delArr(model.addressArr, index)">删除</a>
                  </el-col>
              </template>
              <el-col :md="12" :lg="12" :xl="12">
                <el-button type="primary" size="medium" @click.prevent="insertAddress">添加服务省市</el-button>
              </el-col>
            </el-col>
          </el-row>
        </el-form>
      </el-col>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button type="info" size="medium" @click.prevent="hide()">取消</el-button>
      <el-button v-if="isEdit" type="primary" size="medium" @click.prevent="submit('update')" :loading="loading">保存</el-button>
      <el-button v-if="!isEdit" type="primary" size="medium" @click.prevent="submit('insert')" :loading="loading">提交</el-button>
    </span>
  </el-dialog>
</template>
<script>
import CascadeAddress from '@/components/CascadeAddress'
import {isPhone, isInteger} from '@/utils/validate'
import L from 'lodash'
import {dotData, arrayColumn, delArr} from '@/utils'
export default {
  components: {
    CascadeAddress
  },
  data() {
    return {
      searchLoading: false,
      innerVisible: false,
      isIndeterminate: false,
      cityArr: [],
      nameArr: [],
      workerNameMap: new Map(), // 用map来存放该条师傅所有信息
      oldRowData: {},
      isEdit: false,
      model: {
        workerId: '',
        logAccount: '',
        phone: '',
        plateNumber: '',
        carType: '',
        volume: '',
        addressArr: [
          {
            provinceNo: [],
            cityNos: [],
            area: [],
            checkAll: false,
            citys: []
          }
        ]
      },
      loading: false,
      rules: {
        workerId: [
          { required: true, message: '师傅姓名必须', trigger: 'blur' }
        ],
        logAccount: [
          { required: true, message: '登录账号必须', trigger: 'blur' }
        ],
        phone: [
          {required: true, message: '用户电话必须', trigger: 'blur'},
          {validator: isPhone, message: '电话格式不正确', trigger: 'blur'}
        ],
        plateNumber: [
          { required: true, message: '车牌号必须', trigger: 'blur' }
        ],
        carType: [
          { required: true, message: '车辆类型必选', trigger: 'blur' }
        ],
        volume: [
          { required: true, message: '车辆体积必填', trigger: 'blur' },
          {validator: isInteger, message: '车辆体积必须是整数', type: 'array', trigger: 'blur'}
        ]
      }
    }
  },
  props: {
    carTypeArr: {
      type: Array,
      default() {
        return []
      }
    },
    modifyId: {
      type: String,
      required: true
    }
  },
  create() {
  },
  computed: {
    getTitle() {
      if (this.isEdit) {
        return '修改信息'
      } else {
        return '新增信息'
      }
    }
  },
  watch: {
  },
  methods: {
    isPhone,
    isInteger,
    delArr,
    getCity(item) {
      const province = dotData(item, 'provinceNo')
      if (Array.isArray(province) && province.length > 0) {
        this.$ajax.get('/ms-address/address/findByParentNo', {parentNo: province[0]}).then(response => {
          this.$set(item, 'citys', response.data || [])
        })
      } else {
        this.$set(item, 'citys', [])
      }
    },

    getCityShow(province, index) {
      if (province) {
        this.$ajax.get('/ms-address/address/findByParentNo', {parentNo: province}).then(response => {
          this.$set(this.model.addressArr[index], 'citys', response.data || [])
          if (this.model.addressArr[index].citys.length === this.model.addressArr[index].cityNos.length) {
            this.$set(this.model.addressArr[index], 'checkAll', true)
          }
        })
      } else {
        this.$set(this.model.addressArr[index], 'citys', [])
      }
    },
    handleCheckAllChange(item) {
      if (item.cityNos.length) {
        this.$set(item, 'cityNos', [])
      } else {
        this.$set(item, 'cityNos', arrayColumn(item.citys, 'areaNo'))
      }
      this.handleCheckedCitiesChange(item)
    },
    handleCheckedCitiesChange(item) {
      if (item.cityNos.length === item.citys.length) {
        this.$set(item, 'checkAll', true)
      } else {
        this.$set(item, 'checkAll', false)
      }
    },
    insertAddress() {
      this.model.addressArr.push({provinceNo: [], cityNos: [], area: [], checkAll: false, citys: []})
    },
    beforeClose(done) {
      done()
    },
    show(rowData) {
      const that = this
      this.model.addressArr = []
      this.nameArr = []
      this.innerVisible = true
      this.model.workerId = ''
      this.isEdit = false
      this.$nextTick(_ => {
        this.$refs.addForm.resetFields()
        if (rowData) {
          this.isEdit = true
          this.oldRowData = rowData
          let workerId = dotData(this.oldRowData, 'workerId')
          let workerName = dotData(this.oldRowData, 'workerName')
          let logAccount = dotData(this.oldRowData, 'logAccount')
          this.workerNameMap = new Map()
          this.workerNameMap.set(workerId, {workerId, workerName, logAccount})
          this.model.workerId = workerId
          this.nameArr = [{value: workerId, text: workerName}]
          this.model.phone = dotData(this.oldRowData, 'phone')
          this.model.plateNumber = dotData(this.oldRowData, 'plateNumber')
          this.model.volume = dotData(this.oldRowData, 'volume')
          this.model.carType = dotData(this.oldRowData, 'carType')
          let provinceNoArr = dotData(this.oldRowData, 'provinceNo').split('|')
          let provinceArr = dotData(this.oldRowData, 'province').split('|')
          let cityArr = dotData(this.oldRowData, 'cityNo').split('|')
          for (let i = 0; i < provinceNoArr.length; i++) {
            this.model.addressArr.push({
              provinceNo: [provinceNoArr[i], provinceArr[i]] || [],
              cityNos: cityArr[i].split(','),
              area: [],
              checkAll: false,
              citys: []
            })
            that.getCityShow(provinceNoArr[i], i)
          }
        }
      })
    },
    hide() {
      this.innerVisible = false
    },
    remoteQuery(query) {
      this.searchLoading = true
      this.remoteMethod(query, this)
    },
    remoteMethod: L.debounce((query, _this) => {
      if (!query) {
        _this.searchLoading = false
        return
      }
      _this.$ajax.get('/ms-fahuobao-app/workerUser/getWorkerByName', {name: query, mark: 4}).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          let data = dotData(response, 'data')
          if (Array.isArray(data)) {
            _this.workerNameMap = new Map()
            let temp = []
            data.forEach((v, k) => {
              // 映射
              v.workerName = v.name
              v.workerId = v.userId
              v.logAccount = v.registerPhone
              temp.push({
                text: v.workerName,
                value: v.workerId
              })
              _this.workerNameMap.set(v.workerId, v) // 1首次获取的时候，就将workerId作为键，so
            })
            _this.nameArr = temp
          }
        }
      }).finally(_ => {
        _this.searchLoading = false
      })
    }, 1000),
    submit(operationType) {
      let addressArr = this.model.addressArr
      if (addressArr.length < 1) {
        this.$message({
          type: 'warning',
          message: '请选择服务省市'
        })
        return
      }
      let provinceNoStr = ''
      let cityNoStr = ''
      for (let i = 0; i < addressArr.length; i++) {
        if (!addressArr[i].provinceNo[0]) {
          this.$message({
            type: 'warning',
            message: '请选择服务省'
          })
          return
        }
        provinceNoStr += addressArr[i].provinceNo[0] + '|'
        if (addressArr[i].cityNos.length < 1) {
          this.$message({
            type: 'warning',
            message: '请选择服务市'
          })
          return
        }
        for (let j = 0; j < addressArr[i].cityNos.length; j++) {
          cityNoStr += addressArr[i].cityNos[j] + ','
        }
        cityNoStr = cityNoStr.substring(0, cityNoStr.length - 1) + '|'
      }
      this.$refs.addForm.validate((valid) => {
        if (!valid) {
          return false
        }
        this.loading = true
        let postData = {
          phone: this.model.phone,
          plateNumber: this.model.plateNumber,
          carType: this.model.carType,
          volume: this.model.volume,
          provinceNo: provinceNoStr.substring(0, provinceNoStr.length - 1),
          cityNo: cityNoStr.substring(0, cityNoStr.length - 1)
        }
        let msg = ''
        if (operationType === 'insert') {
          postData.workerId = this.model.workerId
          postData.workerName = this.workerNameMap.get(this.model.workerId)['workerName']
          postData.logAccount = this.getWorkerMapValue('logAccount')
          postData.operation = 'insert'
          msg = '新增成功'
        }
        if (operationType === 'update') {
          postData.operation = 'update'
          postData.id = this.modifyId
          msg = '修改成功'
        }
        this.$ajax.post('/ms-warehouse-order/resourceManage/operateSecondary', postData).then(response => {
          const success = dotData(response, 'success')
          if (success) {
            this.loading = false
            this.hide()
            this.$confirm(msg, '提示', {
              type: 'success',
              center: true,
              confirmButtonText: '确定',
              showCancelButton: false,
              closeOnClickModal: false
            }).then(_ => {
              this.loading = false
              this.hide()
              this.$emit('refresh')
            })
          } else {
            this.hide()
            this.loading = false
            this.$message({
              type: 'error',
              message: '操作失败!'
            })
            this.$emit('refresh')
          }
        }).catch(_ => {
          this.loading = false
        })
      })
    },
    // 根据传进来的id 来get  Map对象里面的某键所对应的值（id 已绑定model,so 不需要传id）
    getWorkerMapValue(key) {
      if (this.workerNameMap.has(this.model.workerId)) {
        let worker = this.workerNameMap.get(this.model.workerId)
        return dotData(worker, key)
      }
      return ''
    }
  }
}
</script>
